package com.winkyle.woodenfish.rx;

import android.util.Log;

import com.winkyle.woodenfish.presenter.BaseMvpPresenter;

import java.net.ConnectException;
import java.net.UnknownHostException;

import rx.Subscriber;

/**
 * @author winkyle
 * @date 2018/06/18
 * @description 网络请求的rxjava封装
 */

public abstract class HttpSubscriber<P extends BaseMvpPresenter,T> extends Subscriber<T> {
    private String TAG = "HttpSubscriber";
    private P mvpPresenter;
    private boolean show;
    private String loadMsg;

    public HttpSubscriber(P mvpPresenter){
        this(mvpPresenter,false);
    }

    public HttpSubscriber(P mvpPresenter,boolean show){
        this(mvpPresenter,show,"加载中");
    }

    public HttpSubscriber(P mvpPresenter,boolean show,String loadMsg){
        this.mvpPresenter = mvpPresenter;
        this.show = show;
        this.loadMsg = loadMsg;
    }

    /**
     * @description 网络请求开始，如果被允许则调起进度条对话框
     * @return
     */
    @Override
    public void onStart() {
        if (mvpPresenter.getMvpView() == null)
            return;
        if(show){
            mvpPresenter.getMvpView().showProgress(loadMsg);
        }
    }


    /**
     * @description 网络请求结束，取消进度条对话框
     * @return
     */
    @Override
    public void onCompleted() {
        if (mvpPresenter.getMvpView() == null)
            return;
        mvpPresenter.getMvpView().hideProgress();
    }

    /**
     * @description 数据访问出错，取消进度条对话框，并判断错误原因
     * @param e
     * @return
     */
    @Override
    public void onError(Throwable e) {
        Log.d(TAG+"onError",e.getMessage());
        if (mvpPresenter.getMvpView() == null)
            return;
        mvpPresenter.getMvpView().hideProgress();
        //如果没联网，则调起进度条，并再次请求发起数据
        if (UnknownHostException.class.equals(e.getClass()) || ConnectException.class.equals(e.getClass())) {
            mvpPresenter.getMvpView().showShortToast("请检查网络");
        }
    }

    /**
     * @description 检查绑定的v层是否已取消绑定，若未取消绑定，则对返回的数据进行处理
     * @param t 返回的数据
     * @return
     */
    @Override
    public void onNext(T t) {
        if(mvpPresenter.getMvpView()==null)
            return;
        processData(t);
    }

    /**
     * @description 对返回的数据进行处理
     * @param t 返回的数据
     * @return
     */
    public abstract void processData(T t);
}
